package com.zyl.pagergallerysave_kt.fragment

import android.os.Bundle
import android.os.Handler
import android.view.*
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.zyl.pagergallerysave_kt.R
import com.zyl.pagergallerysave_kt.adapter.GalleryAdapter
import com.zyl.pagergallerysave_kt.viewModel.GalleryViewModel
import kotlinx.android.synthetic.main.cell_gallery.*
import kotlinx.android.synthetic.main.fragment_gallery.*

class GalleryFragment : Fragment() {
    private lateinit var galleryViewModel: GalleryViewModel
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_gallery, container, false)
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        super.onCreateOptionsMenu(menu, inflater)
        inflater.inflate(R.menu.menu, menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.refresh -> {
                swipeRefreshLayout.isRefreshing = true
                Handler().postDelayed(Runnable {
                    galleryViewModel.fetchData()
                }, 1000)
            }
        }
        return super.onOptionsItemSelected(item)
    }


    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        setHasOptionsMenu(true)
        galleryViewModel = ViewModelProvider(
                this,
                ViewModelProvider.AndroidViewModelFactory(requireActivity().application)
        ).get(GalleryViewModel::class.java)
        galleryViewModel.photoLiveData.value ?: galleryViewModel.fetchData()

        val galleyAdapter = GalleryAdapter()
        recyclerView.apply {
            adapter = galleyAdapter
            layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
        }

        swipeRefreshLayout.setOnRefreshListener {
            galleryViewModel.fetchData()
        }

        galleryViewModel.photoLiveData.observe(this, Observer {
            galleyAdapter.submitList(it)
            swipeRefreshLayout.isRefreshing = false
        })


    }


}